package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import biz.CustomerBiz;
import biz.impl.CustomerBizImpl;
import entity.Customer;

@WebServlet("/RegisterAndLoginServlet.html")
public class RegisterAndLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
     
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String register_username=request.getParameter("register_username");
		CustomerBiz customerBiz = new CustomerBizImpl();
		boolean exists=customerBiz.queryCustomerExists(register_username);
		PrintWriter out=response.getWriter();
		out.print(!exists);//给false会触发 validate
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CustomerBiz customerBiz = new CustomerBizImpl();
		String login_username= request.getParameter("login_username");
		if(login_username!=null){
			//登录
			String userName=login_username;
			String password=request.getParameter("login_password");
			Customer user=customerBiz.loginCustomer(userName, password);
			if(user!=null){
				request.getSession().setAttribute("user",user);
				response.sendRedirect(request.getContextPath()+"/Index.html");
			}else{
				request.setAttribute("login_username",login_username);
				request.setAttribute("loginError", "用户名或密码不正确");
				request.getRequestDispatcher("registerAndLogin.jsp").forward(request, response);
			}
		}else{
			//注册
			String register_username=request.getParameter("register_username");
			String register_password=request.getParameter("register_password");
			String email=request.getParameter("email");
			String phone=request.getParameter("phone");
			Customer customer = new Customer(0,register_username,register_password,phone,new Date(),email,null);
			customerBiz.registerCustomer(customer);
			response.sendRedirect("registerAndLogin.jsp");
		}
	}

}
